package middleware

import (
	"context"
	"eag_arch_layout/internal/conf"
	"eag_arch_layout/internal/model"
	"eag_arch_layout/internal/model/VO"
	"eag_arch_layout/internal/utils"
	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/mitchellh/mapstructure"
	"strings"
)

// JwtAuth2HeaderMw Jwt验证HTTP header 的token
func JwtAuth2HeaderMw(jwtConfig *conf.Jwt, logger log.Logger) middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
			if tr, ok := transport.FromServerContext(ctx); ok {
				logger.Log(log.LevelInfo, "Operation", tr.Operation())
				token := tr.RequestHeader().Get("Authorization")
				if !strings.HasPrefix(token, "Bearer ") {
					return nil, errors.New(500, model.TOKEN_ERROR, "token is illegal")
				}
				token = strings.Replace(token, "Bearer ", "", -1)
				if len(token) > 0 {
					mapClaims, err := utils.ParsingToken(jwtConfig.Secret, token)
					if err != nil {
						//panic("Token contains an invalid value,Pls login again")
						//err := errors.New(500, model.TOKEN_ERROR, "token can not convert")
						logger.Log(log.LevelError, "异常", err)
						return nil, err
					}
					var user VO.CurUserInfo
					if mapClaims != nil {
						d := map[string]interface{}(mapClaims)
						mapstructure.Decode(d, &user)

						ctx = context.WithValue(ctx, model.CUR_USER_KEY, user)
					}
				}

				// Do something on entering
				//tr.Endpoint()
				//spew.Dump(tr.RequestHeader())

			}
			return handler(ctx, req)
		}
	}
}
